from django.shortcuts import render
from django.views import View
from django.core.paginator import Paginator
from django.db.models import Count

from rest_framework.views import APIView

from .models import VisitorModel
from .constants import TABLE_SHOW_FIELDS_MAP
from libs.response import json_response

# Create your views here.


class VisitorListView(View):
    """访问列表视图"""
    def get(self, request):

        page_num = self.request.GET.get("page", 1)

        column_list = list(TABLE_SHOW_FIELDS_MAP.keys())
        column_show_list = list(TABLE_SHOW_FIELDS_MAP.values())

        visitor_queryset = VisitorModel.objects.only(*column_list).all()

        paginator = Paginator(visitor_queryset, 7)  # 分页
        page_obj = paginator.get_page(page_num)

        return render(self.request, "visitors.html", context={
            "table_columns": column_show_list,
            "page_obj": page_obj,
        })


class VisitorListSystemAPIView(APIView):
    """访问列表
     - 返回访问系统类型及其数量
    """

    def get(self, request):
        # 1. 使用分组查询获取表中 system、browser 及其对应的数量
        # 2. 查询到所有条目数量
        # 3. 序列化返回

        system_group_queryset = VisitorModel.objects.values("system").annotate(total=Count("system")).order_by()
        browser_group_queryset = VisitorModel.objects.values("browser").annotate(total=Count("browser")).order_by()
        count = VisitorModel.objects.count()

        system_list = [[item["system"], item["total"]] for item in system_group_queryset]
        browser_list = [[item["browser"], item["total"]] for item in browser_group_queryset]

        data = {
            "systemList": system_list,
            "browserList": browser_list,
            "count": count,
        }

        return json_response(data=data)
